<template>
  <div class="min-h-screen bg-gray-900">
    <!-- 播放器区域 -->
    <div class="flex h-screen">
      <!-- 主播放器 -->
      <div class="flex-1 relative">
        <video
          ref="videoPlayer"
          class="w-full h-full bg-black"
          controls
          @loadedmetadata="onLoadedMetadata"
          @timeupdate="onTimeUpdate"
          @ended="onEnded"
          @error="onError"
        >
          <source v-if="currentMedia?.url" :src="currentMedia.url" />
        </video>

        <!-- 播放控制 -->
        <div class="absolute bottom-4 left-4 right-4 bg-black/50 rounded-lg p-4">
          <div class="flex items-center justify-between">
            <div class="flex items-center space-x-4">
              <button @click="playPrevious" class="text-white hover:text-gray-300">
                <i class="fas fa-step-backward"></i>
              </button>
              <button @click="togglePlay" class="text-white hover:text-gray-300">
                <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
              </button>
              <button @click="playNext" class="text-white hover:text-gray-300">
                <i class="fas fa-step-forward"></i>
              </button>
            </div>
            
            <div class="text-white">
              {{ currentIndex + 1 }} / {{ mediaList.length }}
            </div>
          </div>
        </div>
      </div>

      <!-- 播放列表侧边栏 -->
      <div class="w-80 bg-gray-800 border-l border-gray-700 flex flex-col">
        <div class="p-4 border-b border-gray-700">
          <h3 class="text-lg font-semibold text-white">播放列表</h3>
          <div class="text-sm text-gray-400">{{ mediaList.length }} 个视频</div>
        </div>

        <div class="flex-1 overflow-y-auto">
          <div
            v-for="(media, index) in mediaList"
            :key="media.id"
            class="p-3 border-b border-gray-700 cursor-pointer hover:bg-gray-700"
            :class="{ 'bg-primary-600/20': index === currentIndex }"
            @click="playAtIndex(index)"
          >
            <div class="flex items-center space-x-3">
              <div class="text-sm text-gray-400 w-6">{{ index + 1 }}</div>
              <div class="flex-1">
                <div class="text-sm font-medium text-white truncate">{{ media.title }}</div>
                <div class="text-xs text-gray-400">{{ media.url }}</div>
              </div>
              <div v-if="index === currentIndex && isPlaying" class="text-primary-400">
                <i class="fas fa-play"></i>
              </div>
            </div>
            
            <!-- 进度条 -->
            <div v-if="index === currentIndex" class="mt-2">
              <div class="bg-gray-600 rounded-full h-1">
                <div
                  class="bg-primary-500 h-1 rounded-full transition-all duration-300"
                  :style="{ width: `${progress}%` }"
                ></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 批量操作 -->
        <div class="p-4 border-t border-gray-700">
          <button @click="shuffle" class="btn-secondary w-full mb-2">
            <i class="fas fa-random mr-2"></i>随机播放
          </button>
          <button @click="clearPlaylist" class="btn-secondary w-full">
            <i class="fas fa-trash mr-2"></i>清空列表
          </button>
        </div>
      </div>
    </div>

    <!-- 键盘快捷键提示 -->
    <div v-if="showShortcuts" class="fixed top-4 right-4 bg-gray-800 rounded-lg p-4 shadow-lg">
      <div class="flex justify-between items-center mb-2">
        <h4 class="text-white font-medium">快捷键</h4>
        <button @click="showShortcuts = false" class="text-gray-400 hover:text-white">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <div class="text-sm text-gray-300 space-y-1">
        <div>空格: 播放/暂停</div>
        <div>← →: 快退/快进 10秒</div>
        <div>↑ ↓: 音量调节</div>
        <div>N: 下一首</div>
        <div>P: 上一首</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMediaStore } from '../stores/media'

const mediaStore = useMediaStore()

// Refs
const videoPlayer = ref<HTMLVideoElement>()
const showShortcuts = ref(false)
const currentIndex = ref(0)

// 计算属性
const mediaList = computed(() => mediaStore.mediaList)
const currentMedia = computed(() => mediaList.value[currentIndex.value])
const isPlaying = computed(() => mediaStore.isPlaying)
const progress = computed(() => mediaStore.progress)

// 方法
const playAtIndex = (index: number) => {
  if (index < 0 || index >= mediaList.value.length) return
  
  currentIndex.value = index
  if (videoPlayer.value) {
    videoPlayer.value.src = currentMedia.value?.url || ''
    videoPlayer.value.load()
    videoPlayer.value.play()
    mediaStore.isPlaying = true
  }
}

const playNext = () => {
  const nextIndex = (currentIndex.value + 1) % mediaList.value.length
  playAtIndex(nextIndex)
}

const playPrevious = () => {
  const prevIndex = currentIndex.value === 0 
    ? mediaList.value.length - 1 
    : currentIndex.value - 1
  playAtIndex(prevIndex)
}

const togglePlay = () => {
  if (!videoPlayer.value) return
  
  if (isPlaying.value) {
    videoPlayer.value.pause()
  } else {
    videoPlayer.value.play()
  }
  mediaStore.isPlaying = !isPlaying.value
}

const shuffle = () => {
  const shuffled = [...mediaList.value]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  mediaStore.mediaList = shuffled
  currentIndex.value = 0
  playAtIndex(0)
}

const clearPlaylist = () => {
  mediaStore.mediaList = []
  currentIndex.value = 0
}

const onLoadedMetadata = () => {
  if (!videoPlayer.value) return
}

const onTimeUpdate = () => {
  if (!videoPlayer.value) return
  mediaStore.currentTime = videoPlayer.value.currentTime
  if (currentMedia.value) {
    mediaStore.updatePlaybackHistory(currentMedia.value.id, videoPlayer.value.currentTime)
  }
}

const onEnded = () => {
  mediaStore.isPlaying = false
  // 自动播放下一首
  if (currentIndex.value < mediaList.value.length - 1) {
    playNext()
  }
}

const onError = (e: Event) => {
  console.error('视频播放错误:', e)
}

// 键盘事件
const handleKeyPress = (e: KeyboardEvent) => {
  if (!videoPlayer.value) return
  
  switch (e.code) {
    case 'Space':
      e.preventDefault()
      togglePlay()
      break
    case 'ArrowLeft':
      e.preventDefault()
      videoPlayer.value.currentTime -= 10
      break
    case 'ArrowRight':
      e.preventDefault()
      videoPlayer.value.currentTime += 10
      break
    case 'KeyN':
      e.preventDefault()
      playNext()
      break
    case 'KeyP':
      e.preventDefault()
      playPrevious()
      break
    case 'KeyH':
      e.preventDefault()
      showShortcuts.value = !showShortcuts.value
      break
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeyPress)
  
  if (mediaList.value.length > 0 && videoPlayer.value) {
    videoPlayer.value.src = currentMedia.value?.url || ''
    videoPlayer.value.load()
  }
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyPress)
})
</script>
